
// 页面加载时渲染模拟数据
document.addEventListener("DOMContentLoaded", () => {

  const mcpServerCategories = new Bind({
    el: '#mcp-server-categories',
    data: {
      items: [],
    },
    async asyncData() {
      return {
        items: [
          { name: '浏览器自动化', count: 10 },
          { name: '搜索工具', count: 14 },
          { name: '交流协作工具', count: 32 },
          { name: '开发者工具', count: 127 },
          { name: '娱乐与多媒体', count: 55 },
          { name: '文件系统', count: 10 },
          { name: '金融', count: 14 },
        ]
      }
    },
    events: {

    }
  })

  const mcpServerList = new Bind({
    el: '#servicesGrid',
    data: {
      items: [],
    },
    async asyncData() {
      return {
        items: [
          {
            id: 1,
            title: "Fetch网页内容抓取",
            mode: "hosted",
            tag: "浏览器自动化",
            timeout: 120,
            description: "该服务提供大型语言模型轻松检索和处理网页内容，将HTML转换为markdown格式，以便于模型检索使用。",
            provider: "@modelcontextprotocol",
            provider_url: "https://github.com/modelcontextprotocol/mcp-server-fetch",
          },
          {
            id: 2,
            title: "Fetch网页内容抓取",
            mode: "hosted",
            tag: "浏览器自动化",
            timeout: 120,
            description: "该服务提供大型语言模型轻松检索和处理网页内容，将HTML转换为markdown格式，以便于模型检索使用。",
            provider: "@modelcontextprotocol",
            provider_url: "https://github.com/modelcontextprotocol/mcp-server-fetch",
          }
        ]
      }
    },
    events: {

    }
  })

  // 搜索事件
  const searchInput = document.getElementById('search-input');
  searchInput.addEventListener('input', () => {
    mcpServerList.refresh()
  });

  // 服务类型切换逻辑（示例：点击切换 active 类）
  const typeBtns = document.querySelectorAll(".tag");
  typeBtns.forEach((btn) => {
    btn.addEventListener("click", () => {
      typeBtns.forEach((b) => b.classList.remove("active"));
      btn.classList.add("active");
      // 实际开发需根据类型过滤接口数据，这里仅做样式演示
      mcpServerCategories.refresh()
      mcpServerList.refresh()
    });
  });

  // 加载更多按钮
  const loadMoreBtn = document.querySelector('.load-more');
  loadMoreBtn.addEventListener('click', function () {
    // 模拟加载中状态
    this.textContent = '加载中...';
    mcpServerList.refresh()

    // 模拟异步加载
    setTimeout(() => {
      // 恢复按钮状态
      this.textContent = '加载更多';

      // 这里可以添加加载更多服务卡片的逻辑
    }, 1000);
  });


  const mcpModal = new Bind({
    el: '#mcpModal',
    data: {
      modal_title: '',
      title: '',
      server_name: '',
      server_url: '',
      mode: '',
      tag: '',
      timeout: '',
      headers: '',
      description: '',
      provider: '',
      provider_url: '',
    },
  })

  // 创建MCP功能
  const createMcpBtn = document.getElementById('createMcpBtn');
  const closeModal = document.getElementById('closeModal');
  const cancelBtn = document.getElementById('cancelBtn');
  const submitBtn = document.getElementById('submitBtn');
  const mcpForm = document.getElementById('mcpForm');

  // 显示创建MCP模态框
  createMcpBtn.addEventListener('click', () => {
    mcpModal.setData({ 
      modal_title: '创建新的MCP服务', 
      title: '',
      server_name: '',
      server_url: '',
      mode: 'stdio',
      headers: '',
      tag: '',
      timeout: '',
      description: '',
      provider: '',
      provider_url: '',
    })
  });

  // 关闭模态框
  closeModal.addEventListener('click', () => {
    mcpModal.style.display = 'none';
  });

  cancelBtn.addEventListener('click', () => {
    mcpModal.style.display = 'none';
  });

  submitBtn.addEventListener('click', (event) => {
    // event.preventDefault();
    mcpForm.submit();
  });

  // 点击模态框外部关闭
  window.addEventListener('click', (event) => {
    if (event.target === mcpModal) {
      mcpModal.style.display = 'none';
    }
  });




  // 文件上传处理
  const fileInput = document.getElementById('fileInput');
  const uploadArea = document.getElementById('upload-mcp-server');
  const fileInfo = document.getElementById('file-info');
  const modeSelect = document.getElementById('modeSelect');
  const uploadGroup = document.getElementById('uploadGroup');
  const mcpServerUrl = document.getElementById('mcpServerUrl');
  const mcpServerHeaders = document.getElementById('mcpServerHeaders');

  // 根据选择的mode类型显示/隐藏上传区域
  modeSelect.addEventListener('change', () => {
    if (modeSelect.value === 'stdio') {
      uploadGroup.style.display = 'block';
    } else {
      uploadGroup.style.display = 'none';
      mcpServerUrl.style.display = 'block';
      mcpServerHeaders.style.display = 'block';
      // // 重置文件选择
      // fileInput.value = '';
      // fileInfo.style.display = 'none';
      // uploadArea.textContent = '点击上传服务';
    }
  });

  // 点击上传区域触发文件选择
  uploadArea.addEventListener('click', (e) => {
    fileInput.click();
  });


  // 处理表单提交
  mcpForm.addEventListener('submit', async (event) => {
    event.preventDefault();

    // 获取表单数据
    const formData = new FormData(mcpForm);
    const fileInput = document.getElementById('fileInput');

    // 检查如果选择了stdio模式但没有选择文件
    if (modeSelect.value === 'stdio' && fileInput.files.length === 0) {
      alert('请选择要上传的zip文件');
      return;
    }

    // 创建用于上传的FormData
    const uploadFormData = new FormData();
    uploadFormData.append('server_name', formData.get('server_name'));
    uploadFormData.append('description', formData.get('description'));

    // 只有在选择了文件时才添加文件到FormData
    if (fileInput.files.length > 0) {
      uploadFormData.append('file', fileInput.files[0]);
    }

    try {
      // 上传文件
      const response = await fetch('/api/mcp/upload-server', {
        method: 'POST',
        body: uploadFormData
      });

      if (response.ok) {
        const result = await response.json();
        alert('MCP服务器上传成功: ' + result.message);
        mcpModal.style.display = 'none';
        // 重置表单
        mcpForm.reset();
        document.getElementById('file-info').style.display = 'none';
        document.getElementById('upload-mcp-server').textContent = '点击上传服务';
        // 隐藏上传区域（因为重置表单会将mode设为默认值stdio）
        uploadGroup.style.display = 'none';
      } else {
        const error = await response.json();
        alert('上传失败: ' + (error.detail || '未知错误'));
      }
    } catch (error) {
      console.error('上传错误:', error);
      alert('上传过程中发生错误: ' + error.message);
    }
  });



  // 文件选择后处理
  fileInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      // 检查文件类型
      if (!file.name.endsWith('.zip')) {
        alert('只能上传.zip文件');
        fileInput.value = '';
        fileInfo.style.display = 'none';
        return;
      }

      // 检查文件大小 (20MB = 20 * 1024 * 1024 bytes)
      const maxSize = 20 * 1024 * 1024;
      if (file.size > maxSize) {
        alert('文件大小不能超过20MB');
        fileInput.value = '';
        fileInfo.style.display = 'none';
        return;
      }

      // 显示文件信息
      fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
      fileInfo.style.display = 'block';
      uploadArea.textContent = '重新选择文件';
    } else {
      fileInfo.style.display = 'none';
      uploadArea.textContent = '点击上传服务';
    }
  });
});
